//
//  LoginViewController.m
//  FruitsWholesaler
//
//  Created by sgone-2 on 15/12/6.
//  Copyright © 2015年 sgone. All rights reserved.
//

#import "LoginViewController.h"
#import "Reg1ViewController.h"
#import "ForgetPswViewController.h"
#import "CustomViewController.h"
#import "AFNetworking.h"
#import "LoginViewController.h"
#import "MBProgressHUD+MJ.h"

#import "DataSingleton.h"
#import "Reg2ViewController.h"



#define view2Height 90
@interface LoginViewController ()<UITextFieldDelegate>


@property(nonatomic,strong)  UITextField *textPhone;
@property(nonatomic,strong)  UITextField * textPassword;
@property(nonatomic,strong)  UIButton *btnForgot;
@property(nonatomic,strong)  UIButton *btnFogin;
@property(nonatomic,strong)  UIButton *btnRegister;
//网路请求
@property(nonatomic,strong)AFHTTPSessionManager *manager;


@property(nonatomic,strong) DataSingleton *dh;


//添加键盘撤销button键
@property(nonatomic,strong) UIButton *btnMengban;

@end

@implementation LoginViewController


//afnetworking网络请求数据
- (AFHTTPSessionManager *)manager
{
    if (_manager == nil) {
        _manager  = [AFHTTPSessionManager manager];
    }
    return _manager;
    
    
}



- (void)viewDidLoad {
    [super viewDidLoad];
//    self.title = @"登  录";
//    self.titleLabel.font = [UIFont systemFontOfSize:20];
    self.titleLabel.font = [UIFont boldSystemFontOfSize:19];
    
    
    self.dh = [DataSingleton sharedDataSingleton];
    
    
    self.titleLabel.text = @"登  录";
    self.topView.hidden = YES;
    
   
    self.view.backgroundColor =  BACKGROUND1;
    
    [self initImage];
    
    [self initView];
    

    
}



-(void)initImage
{
   
    UIImageView *image1 = [[UIImageView alloc]initWithFrame:CGRectMake((ViewWidth-90)/2, 50, 110, 90)];
    image1.image = [UIImage imageNamed:@"mian"];
    [self.view addSubview:image1];
}




#pragma mark 进行登录的操作
-(void)initView
{


    
    //设置前后的空白位置
    UIView *view2 = [[UIView alloc]initWithFrame:CGRectMake(0, 74+20+view2Height, 10, 50)];
    view2.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view2];
    
    UIView *view23 = [[UIView alloc]initWithFrame:CGRectMake(ViewWidth-15, 74+20+view2Height, 15, 50)];
    view23.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view23];
    
    
    
    
    self.textPhone = [[UITextField alloc]initWithFrame:CGRectMake(10, 74+20+view2Height, ViewWidth-15-10, 50)];
    [self.view addSubview:self.textPhone];
    self.textPhone.placeholder = @"请输入手机号";
    self.textPhone.clearButtonMode = UITextFieldViewModeAlways;
    self.textPhone.backgroundColor = [UIColor whiteColor];
    self.textPhone.delegate = self;
    self.textPhone.keyboardType = UIKeyboardTypeNumberPad;
    
    
    
    //设置前后的空白位置
    UIView *view3 = [[UIView alloc]initWithFrame:CGRectMake(0, 74+20+50+view2Height, 10, 50)];
    view3.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view3];
    
    UIView *view33 = [[UIView alloc]initWithFrame:CGRectMake(ViewWidth-15, 74+20+50+view2Height, 15, 50)];
    view33.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view33];


    
    self.textPassword = [[UITextField alloc]initWithFrame:CGRectMake(10, 74+20+50+view2Height, ViewWidth-15-10, 50)];
    [self.view addSubview:self.textPassword];
    self.textPassword.placeholder = @"请输入密码";
    self.textPassword.clearButtonMode = UITextFieldViewModeAlways;
    self.textPassword.backgroundColor = [UIColor whiteColor];
    self.textPassword.delegate = self;
    self.textPassword.returnKeyType = UIReturnKeyDone;
    self.textPassword.secureTextEntry = YES;
    
    //添加中间线
    UIView *view1 = [[UIView alloc]initWithFrame:CGRectMake(10, 74+20+49+view2Height, ViewWidth-15-10, 1 )];
    view1.backgroundColor = BACKGROUND1;
    [self.view addSubview:view1];
    
    
    
    //添加忘记密码
    
    self.btnForgot = [[UIButton alloc]initWithFrame:CGRectMake(0, 74+20+50+50+20+view2Height, ViewWidth, 50)];
    [self.btnForgot setTitle:@"忘记密码?" forState:UIControlStateNormal];
//    self.btnFogin.titleLabel.textAlignment = NSTextAlignmentRight;
    
    [self.btnForgot setTitleEdgeInsets:UIEdgeInsetsMake(0, ViewWidth-15 -90, 10, 0)];
    
    self.btnForgot.titleLabel.font = [UIFont boldSystemFontOfSize:17];
    [self.btnForgot setTitleColor:BenSe_COLOR forState:UIControlStateNormal];
    [self.view addSubview:self.btnForgot];
    
    [self.btnForgot addTarget:self action:@selector(forget:) forControlEvents:UIControlEventTouchUpInside];
    self.btnForgot.enabled = YES;
    
    
    
    //设置登录以及注册
    self.btnFogin = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [self.btnFogin.layer setMasksToBounds:YES];
    [self.btnFogin.layer setCornerRadius:3.0];
    self.btnFogin.frame = CGRectMake(20, 258+view2Height, ViewWidth-40, 44);
    [self.btnFogin setTitle:@"登      录" forState:UIControlStateNormal];
    self.btnFogin.titleLabel.font = [UIFont boldSystemFontOfSize:19];
    [self.btnFogin setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.view addSubview:self.btnFogin];
    self.btnFogin.backgroundColor = BenSe_COLOR;
//    self.btnFogin.buttonType = UIButtonTypeSystem;
    [self.btnFogin addTarget:self action:@selector(login:) forControlEvents:UIControlEventTouchUpInside];

    
    self.btnRegister = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [self.btnRegister.layer setMasksToBounds:YES];
    [self.btnRegister.layer setCornerRadius:3.0];
    self.btnRegister.frame = CGRectMake(20, 240+44+44+view2Height, ViewWidth-40, 44);
    [self.btnRegister setTitle:@"注      册" forState:UIControlStateNormal];
    self.btnRegister.titleLabel.font = [UIFont boldSystemFontOfSize:19];
    [self.btnRegister setTitleColor:BenSe_COLOR forState:UIControlStateNormal];
    [self.view addSubview:self.btnRegister];
    self.btnRegister.backgroundColor = [UIColor whiteColor];
    [self.btnRegister addTarget:self action:@selector(zhucei:) forControlEvents:UIControlEventTouchUpInside];

    
    
    
    
    
    
    //添加撤销键盘操作
    self.btnMengban = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, ViewWidth, ViewHeight)];
    [self.view addSubview:self.btnMengban];
    [self.btnMengban addTarget:self action:@selector(chexiao:) forControlEvents:UIControlEventTouchUpInside];
    self.btnMengban.hidden = NO;
    
    


}


#pragma mark 撤销键盘
-(void)chexiao:(id)sender
{


    [self.textPhone resignFirstResponder];
    [self.textPassword resignFirstResponder];

    self.btnMengban.hidden = YES;

    
    if (ViewHeight == 480) {
        
        [UIView animateWithDuration:0.25 animations:^{
            
            if (self.view.y == -100) {
                
                self.view.y = 0;
            }
            
        }];
    }
}




//忘记密码
-(void)forget:(id)sender
{
    ForgetPswViewController *forget = [[ForgetPswViewController alloc]initWithNibName:nil bundle:nil];
    
    
    [self presentViewController:forget animated:YES completion:nil];
    
//    [self.navigationController pushViewController:forget animated:YES];



}


#pragma mark 进行登录
-(void)login:(id)sender
{
    
    if (self.textPhone.text.length == 0) {
        [self.view makeToast:@"手机号码不能为空"];
        return;
  
        
    }
    
    
    if (self.textPassword.text.length == 0) {
        [self.view makeToast:@"密码不能为空"];
        return;

        
    }


    NSString *password = md5(self.textPassword.text);
    
    
    //获取当前应用的版本号
    NSDictionary *infoDic = [[NSBundle mainBundle]infoDictionary];
    NSString *currentVersion = [infoDic objectForKey:@"CFBundleShortVersionString"];
//    NSLog(@"lilili %@    ",currentVersion);
    

    
    //网络请求验证手机号以及密码
    NSString *urlStr = [NSString stringWithFormat:@"%@login",SERVER_ADDRESS];
    NSDictionary *parmas = @{@"wTel" : self.textPhone.text ,@"passwd" : password ,@"app_version" : currentVersion , @"device_type" : @"1"};
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [self.manager POST:urlStr parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
        
        if ([responseObject[@"error_flag"] intValue] == 0) {
            
            
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
            
            CustomViewController *customer = [[CustomViewController alloc]initWithNibName:nil bundle:nil];
            
            
            
//            NSLog(@"eeeeeeeeeee %@",responseObject[@"data"]);
            
            //市场列表
            self.dataHandler.shichanglist = [responseObject[@"data"] objectForKey:@"market"];
            [self.dataHandler saveLocalData:@"market" value:self.dataHandler.shichanglist];
    
            
            
            
            //不能存储NULL的类型,全部转换为字符串

            NSString *latitude = [NSString stringWithFormat:@"%@",[[responseObject[@"data"]objectForKey:@"wholesaler"] objectForKey:@"addX"]];
            
            NSString *longtitude =[NSString stringWithFormat:@"%@",[[responseObject[@"data"]objectForKey:@"wholesaler"] objectForKey:@"addY"]];

            
            self.dataHandler.latitude = latitude;
            [self.dataHandler saveLocalData:@"addX" value:self.dataHandler.latitude];
            
            self.dataHandler.longtitude =longtitude;
            [self.dataHandler saveLocalData:@"addY" value:self.dataHandler.longtitude];
            
            
            
            NSString *dizhi = [NSString stringWithFormat:@"%@",[[responseObject[@"data"] objectForKey:@"wholesaler"] objectForKey:@"address"]];
            
            //具体地址
            self.dataHandler.dizhi = dizhi;
            [self.dataHandler saveLocalData:@"address" value:self.dataHandler.dizhi];
         
            
            NSString *newdizhi =[NSString stringWithFormat:@"%@%@%@",[[responseObject[@"data"] objectForKey:@"wholesaler"] objectForKey:@"province"],[[responseObject[@"data"] objectForKey:@"wholesaler"] objectForKey:@"city"],[[responseObject[@"data"] objectForKey:@"wholesaler"] objectForKey:@"town"]];
            
            //新的详细地址
            self.dataHandler.newdizhi = newdizhi;
          
            [self.dataHandler saveLocalData:@"address1" value:self.dataHandler.newdizhi];
            
            
        
            
            NSString *fanwei =[ NSString stringWithFormat:@"%@",[[responseObject[@"data"] objectForKey:@"wholesaler"] objectForKey:@"push_radius"]];
            
            //送货范围
            self.dataHandler.fanwei =fanwei;
            [self.dataHandler saveLocalData:@"push_radius" value:self.dataHandler.fanwei];
            
            
            NSString *jiage =[NSString stringWithFormat:@"%@",[[responseObject[@"data"] objectForKey:@"wholesaler"] objectForKey:@"start_price"]];

            
            //起送价格
            self.dataHandler.jiage =  jiage;
            [self.dataHandler saveLocalData:@"start_price" value:self.dataHandler.jiage];
            
            
    
            NSString *juli =[ NSString stringWithFormat:@"%@",[[responseObject[@"data"] objectForKey:@"wholesaler"] objectForKey:@"near_range"]];

            //送货距离
            self.dataHandler.juli =  juli;
            [self.dataHandler saveLocalData:@"near_range" value:self.dataHandler.juli];
            
            
            
            //远距离
            NSString *juli2 =[ NSString stringWithFormat:@"%@",[[responseObject[@"data"] objectForKey:@"wholesaler"] objectForKey:@"far_range"]];
            self.dataHandler.juli2 = juli2;
            [self.dataHandler saveLocalData:@"far_range" value:self.dataHandler.juli2];
            
            
            
            NSString *yunfei = [NSString stringWithFormat:@"%@",[[responseObject[@"data"] objectForKey:@"wholesaler"] objectForKey:@"near_price"]];
            //送货运费
            self.dataHandler.yunfei = yunfei;
            [self.dataHandler saveLocalData:@"near_price" value:self.dataHandler.yunfei];

            
            
            NSString *dianshu = [NSString stringWithFormat:@"%@",[[responseObject[@"data"] objectForKey:@"wholesaler"] objectForKey:@"start_point"]];
            //起送店数
            self.dataHandler.dianshu = dianshu;
            [self.dataHandler saveLocalData:@"start_point" value:self.dataHandler.dianshu];

            
            
            
            NSString *zjyunfei = [NSString stringWithFormat:@"%@", [[responseObject[@"data"] objectForKey:@"wholesaler"] objectForKey:@"over_price"]];
            //额外增加运费
            self.dataHandler.zjyunfei = zjyunfei;
            [self.dataHandler saveLocalData:@"over_price" value:self.dataHandler.zjyunfei];
            
            
            
            
            
            
            NSString *shichang = [NSString stringWithFormat:@"%@", [[responseObject[@"data"] objectForKey:@"wholesaler"] objectForKey:@"market"]];
            //保存的市场（单个）
            
            self.dataHandler.shichang =shichang;
            [self.dataHandler saveLocalData:@"market" value:self.dataHandler.shichang];
            //所需的城市
            self.dataHandler.shi = [NSString stringWithFormat:@"%@",[[responseObject[@"data"] objectForKey:@"wholesaler"] objectForKey:@"city"]];
            [self.dataHandler saveLocalData:@"city" value:self.dataHandler.shi];
            
            
            
            
            

            
            
            //存储手机号
//            self.dataHandler.phone =  [[responseObject[@"data"]objectForKey:@"wholesaler"] objectForKey:@"wTel"];
            
//            self.dh.phone = self.textPhone.text;
            
            
            self.dh.phone =[[responseObject[@"data"]objectForKey:@"wholesaler"] objectForKey:@"wTel"];
            
            [self.dh saveLocalData:@"wTel" value:self.dh.phone];
            
            self.dh.password = self.textPassword.text;
            [self.dh saveLocalData:@"password" value:self.dh.password];
            
            //utoken
            
            self.dh.uToken =  [[responseObject[@"data"]objectForKey:@"wholesaler"] objectForKey:@"uToken"];
            [self.dh saveLocalData:@"uToken" value:self.dh.uToken];
            
            //名字
            self.dh.name = [[responseObject[@"data"]objectForKey:@"wholesaler"] objectForKey:@"wholesaler_name"];
            [self.dh saveLocalData:@"wholesaler_name" value:self.dh.name];


            //保存所有的数据
            
            self.dh.userDic = [NSMutableDictionary dictionaryWithDictionary:[responseObject[@"data"] objectForKey:@"wholesaler"]];
            [self.dh saveLocalData:@"data" value:self.dh.userDic];
            [self presentViewController:customer animated:NO completion:nil];

            [[NSUserDefaults standardUserDefaults]setObject:[[responseObject[@"data"] objectForKey:@"wholesaler"] objectForKey:@"wId"] forKey:@"wId"];
            
            
            
            
            
        }
        else
        {
        
                [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
            NSString *str = [NSString stringWithFormat:@"%@",[responseObject objectForKey:@"result_msg"]];
            UIAlertView *alter =[[UIAlertView alloc]initWithTitle:@"提示" message:str delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alter show];
            
        
        
        }
        
        
        
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
       
        UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请检查网络！" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alter show];
        
        
        
    }];

    

}



#pragma mark进行注册
-(void)zhucei:(id)sender
{
    
    Reg1ViewController *reg2 = [[Reg1ViewController alloc]initWithNibName:nil bundle:nil];
//    Reg2ViewController *reg2 = [[Reg2ViewController alloc]initWithNibName:nil bundle:nil];
    
    [self presentViewController:reg2 animated:YES completion:nil];
    

}



-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{

    
    if ( textField == self.textPassword || textField == self.textPhone) {
        
        
        self.btnMengban.hidden = NO;
     
    }
    
    
    if (ViewHeight == 480 && textField == self.textPassword) {
        [UIView animateWithDuration:0.25 animations:^{
            
            if (self.view.y == 0) {
                
                self.view.y = -100;
            }
            
        }];
    }
    return YES;




}



-(BOOL)textFieldShouldReturn:(UITextField *)textField
{

    [self.textPhone resignFirstResponder];
    [self.textPassword resignFirstResponder];

    self.btnMengban.hidden = YES;

    
    if (ViewHeight == 480) {
        
        [UIView animateWithDuration:0.25 animations:^{
            
            if (self.view.y == -100) {
                
                self.view.y = 0;
            }
            
        }];
    }
    
    
    return YES;


}
@end
